﻿using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Web;

namespace Common
{
    public static class HtmlHelpers
    {
        public static HtmlString ReplaceQueryString(this IHtmlHelper htmlHelper, string key, string value)
        {
            var context = htmlHelper.ViewContext.HttpContext;
            var path = context.Request.Path.ToString();
            var qs = HttpUtility.ParseQueryString(context.Request.QueryString.ToString());
            qs.Set(key, value);
            return new HtmlString(string.Format("{0}?{1}", path, qs.ToString()));
        }

        public static HtmlString ReplaceQueryString(this IHtmlHelper htmlHelper, Dictionary<string, string> parms)
        {
            var context = htmlHelper.ViewContext.HttpContext;
            var path = context.Request.Path.ToString();
            var qs = HttpUtility.ParseQueryString(context.Request.QueryString.ToString());
            foreach (var item in parms)
            {
                qs.Set(item.Key, item.Value);
            }
            return new HtmlString(string.Format("{0}?{1}", path, qs.ToString()));
        }

        public static HtmlString ToDate(this IHtmlHelper htmlHelper, object value)
        {
            if (value == null) return new HtmlString("");
            DateTime dt;
            var str = "";
            if (DateTime.TryParse(value.ToString(), out dt))
                str = dt.ToString("yyyy-MM-dd");
            if (str == "1900-01-01")
                str = "";
            return new HtmlString(str);
        }

        public static HtmlString ToDateTime(this IHtmlHelper htmlHelper, object value)
        {
            if (value == null) return new HtmlString("");
            DateTime dt;
            if (DateTime.TryParse(value.ToString(), out dt))
                return new HtmlString(dt.ToString("yyyy-MM-dd HH:mm:ss"));
            return new HtmlString("");
        }
    }
}
